﻿using System;
using System.CodeDom;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using Com;
using DAL.MySQL;
using Models;
using PetaPoco;

namespace Core
{
    public class categoryCore
    {
        private readonly categoryDAL dal = new categoryDAL();

        public categoryEntity GetOne(int id)
        {
            return dal.GetOne(id) == null ? new categoryEntity() : dal.GetOne(id);
        }

        public categoryEntity Save(categoryEntity model)
        {
            return dal.Save(model);
        }
        public void ClearTreeCache()
        {
            HttpContext.Current.Cache.Remove("categorytree");
        }

        public int UpdateHits(int ID)
        {
            return dal.UpdateHits(ID);
        }
        public int Update(object obj, int ID)
        {
            ClearTreeCache();
            return dal.Update(obj, ID);
        }
        public List<categoryEntity> GetTree()
        {
            if (CacheHelper.Get<List<categoryEntity>>("categorytree") != null)
            {
                return CacheHelper.Get<List<categoryEntity>>("categorytree");
            }
            var rootList = GetTreeCategory(0);
            CacheHelper.Insert("categorytree",rootList,60);
            return rootList;
        }
        public List<categoryEntity> GetTreeCategory(int fid)
        {
            var rootList = dal.GetList(" and fid=@0", "ordnum desc", fid);
            foreach (categoryEntity categoryEntity in rootList)
            {
                categoryEntity.children = GetTreeCategory(categoryEntity.ID);
            }

            return rootList;
        }
        public bool Del(int id)
        {
            ClearTreeCache();
            return dal.Del(id);
        }
        public bool Del(categoryEntity model)
        {
            ClearTreeCache();
            return dal.Del(model);
        }
        public List<categoryEntity> GetList(int top,string where,string order,params object[] args)
        {
            if(top>0)
                return dal.GetPageList(1, top, where, order, args).Items;
            return dal.GetList(where, order, args);
        }
        public Page<categoryEntity> GetPage(int page,int pagesize,string where ,string order, params object[] args)
        {
            return dal.GetPageList(page, pagesize, where, order, args);
        }
    }
}
